package com.wj.facedetect.net;

import android.util.Log;

import com.wj.facedetect.bean.common.NullValueHandler;
import com.wj.facedetect.view.IBaseView;
import com.wj.facedetect.view.IViewForFile;

import okhttp3.Call;

public class CommonCallBack extends BaseCallBack<BaseResponse> {
    private static final String TAG = "CommonCallBack";
    private int what;
    private IBaseView view;
    private Object carryObj;


    public CommonCallBack(int what, IBaseView view, Class beanCls, Object carryObj) {
        super(new BaseResponse(beanCls));
        this.what = what;
        this.view = view;
        this.carryObj = carryObj;
    }

    @Override
    public final void onError(Call call, Exception e, int id) {
        //网络请求失败
        Log.e(TAG, "------onError--->" + e.getMessage());
        onErrorPre(carryObj);
        view.onError(what, e, carryObj);
    }

    @Override
    public final void onResponse(BaseResponse response, int id) {
        //网络请求成功
        if (response.isSuccess()) {
            Object data = response.getResults();
            onSuccessPre(data, carryObj);
            view.onSuccess(what, data, carryObj);
        } else {
            int code = response.getCode();
            String message = response.getMessage();
            onFailPre(code, message, carryObj);
            view.onFail(what, code, message, carryObj);
        }
    }

    @Override
    public void inProgress(float progress, long total, int id) {
        if (view instanceof IViewForFile) {
            if (total < 0) {
                total = Long.MIN_VALUE;
            }
            if (progress < 0) {
                progress = Math.abs(progress);
            }
            IViewForFile viewForFile = (IViewForFile) view;
            viewForFile.onProgress(what, progress, total, carryObj);
        }
    }

    protected void onErrorPre(Object carryObj) {
    }

    protected void onFailPre(int errorCode, String errorMsg, Object carryObj) {
    }

    protected void onSuccessPre(Object data, Object carryObj) {
    }

    /**
     * demo模拟调用
     *
     * @param data
     */
    public CommonCallBack onSuccessForDemo(Object data) {
        if (data instanceof NullValueHandler) {
            ((NullValueHandler) data).handNullValue();
        } else if (data instanceof Object[]) {
            Object[] objects = (Object[]) data;
            for (Object obj : objects) {
                if (obj instanceof NullValueHandler) {
                    ((NullValueHandler) obj).handNullValue();
                }
            }
        }
        Log.i(TAG, "------onSuccessForDemo------>" + data);
        onSuccessPre(data, carryObj);
        view.onSuccess(what, data, carryObj);
        return this;
    }
}
